package com.aco.party.web.controller.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.aco.party.common.web.BaseController;
import com.aco.party.util.Uploader;
@Controller
public class ImageUpController extends BaseController{
	@RequestMapping("/uploadimage")
	public void imageUp(HttpServletResponse response,HttpServletRequest request) throws Exception{
		request.setCharacterEncoding( Uploader.ENCODEING );
		response.setCharacterEncoding( Uploader.ENCODEING );

		String currentPath = request.getRequestURI().replace( request.getContextPath(), "" );
		String rootDir=request.getContextPath();
		String configDir=rootDir+File.separator+"ueditor1_3_6-utf8-jsp"+File.separator+"jsp"+File.separator;
		File currentFile = new File( currentPath );

		currentPath = currentFile.getParent() + File.separator;

		//加载配置文件
		/*
		String propertiesPath = request.getSession().getServletContext().getRealPath( configDir + "config.properties" );
		Properties properties = new Properties();

		try {
		    properties.load( new FileInputStream( propertiesPath ) );
		} catch ( Exception e ) {
		    //加载失败的处理
		    e.printStackTrace();
		}
	*/
		List<String> savePath = Arrays.asList( "ueditor".split( "," ) );


		//获取存储目录结构
		if ( request.getParameter( "fetch" ) != null ) {

		    response.setHeader( "Content-Type", "text/javascript" );

		    //构造json数据
		    Iterator<String> iterator = savePath.iterator();

		    String dirs = "[";
		    while ( iterator.hasNext() ) {

		        dirs += "'" + iterator.next() +"'";

		        if ( iterator.hasNext() ) {
		            dirs += ",";
		        }

		    }
		    dirs += "]";
		    response.getWriter().print( "updateSavePath( "+ dirs +" );" );
		    return;

		}

		Uploader up = new Uploader(request);

		// 获取前端提交的path路径
		String dir = request.getParameter( "dir" );


		//普通请求中拿不到参数， 则从上传表单中拿
		if ( dir == null ) {
			dir = up.getParameter("dir");
		}

		if ( dir == null || "".equals( dir ) ) {

		    //赋予默认值
		    dir = savePath.get( 0 );

		    //安全验证
		} else if ( !savePath.contains( dir ) ) {

		    response.getWriter().print( "{'state':'\\u975e\\u6cd5\\u4e0a\\u4f20\\u76ee\\u5f55'}" );
		    return;

		}
		String myPath="system/file/";
		up.setSavePath(myPath+ dir );
		String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
		up.setAllowFiles(fileType);
		up.setMaxSize(500 * 1024); //单位KB
		up.upload();
		response.getWriter().print("{'original':'"+up.getOriginalName()+"','url':'"+up.getUrl()+"','title':'"+up.getTitle()+"','state':'"+up.getState()+"'}");
	}
}
